from flask import Blueprint,request,jsonify,send_file,redirect
from flask_restful import reqparse
import json, random, time, requests,string
from util.myredis import r
from captcha.image import ImageCaptcha
from models.user import *
from util.myjwt import myjwt
from util.smscode import sms_code

user_blue = Blueprint("userblue",__name__)

# 图片验证码
@user_blue.route("/getImageCode")
# def getImageCode():
#     # 生成图片验证码 text文字   image图片流
#     name, text, image = captcha.generate_captcha()
#     # 从页面获取uuid做为redis key
#     uuid = request.args.get("uuid")
#     # 存入redis
#     r.str_setex(uuid, text, 300)
#     # 以流的方式生成图片验证码
#     res = make_response(image)
#     res.headers["Content-Type"] = 'image/jpg'
#     return res

def getImageCode():
    # 随机生成验证码
    req = reqparse.RequestParser()
    req.add_argument('uuid')
    args = req.parse_args()
    uuid = args['uuid']
    print('uuid', uuid)
    # 随机生成4个字母加数字的验证码
    code = ''.join(random.sample(string.ascii_lowercase + string.hexdigits, 4))
    img = ImageCaptcha()
    img_png = img.generate(code)
    print(code)
    r.str_setex(uuid,code,3600)
    return send_file(img_png,mimetype="png")

@user_blue.route("/sendsms", methods=['POST'])
def getSmsCode():
    req = reqparse.RequestParser()
    req.add_argument('uuid')
    req.add_argument('mobile')
    req.add_argument('imagecode')
    args = req.parse_args()
    uuid = args['uuid']
    mobile = args['mobile']
    imagecode = args['imagecode']
    print('uuid', uuid)
    # 从redis中取出来 图片验证码
    imgcode = r.str_get(uuid)

    if imgcode:
        print('imgcode', imgcode)
        print(imagecode)
        if imgcode.lower().decode() == imagecode.lower():
            # 验证一分钟内只能发一次
            mcode = r.str_get(mobile)
            if mcode:
                return jsonify({'code': 10012, 'msg': '一分钟内不能重复发'})
            # 调用短信平台
            # 生成5位随机数
            smscode = random.randint(1000,9999)
            flag = sms_code(mobile, smscode)
            print('flag', flag)
            if flag:
                # 手机验证码存入redis
                r.str_setex(mobile, smscode, 60)
                # 删除图片验证码
                r.del_key(uuid)
                # 返回结果
                return jsonify({'code': 200, 'msg': '发送成功'})

            else:
                return jsonify({'code': 10013, 'msg': '发送验证码失败'})
        else:
            return jsonify({'code': 10011, 'msg': '图片验证码错误'})
    else:
        return jsonify({'code': 10010, 'msg': '图片验证码不存在'})



@user_blue.route("/login", methods=['POST'])
def login():
    # 获取前端数据
    req = reqparse.RequestParser()
    req.add_argument('sms')
    req.add_argument('mobile')
    args = req.parse_args()
    smscode = args['sms']
    mobile = args['mobile']
    print(smscode,mobile)
    # 判断数据是否完整
    if not all([smscode,mobile]):
        return jsonify({
            'code': 400,
            'mobile': '数据不完整'
        })

    # 从redis中根据手机号取出验证码
    code = r.str_get(mobile)
    if code:
        # 判断两个验证码是否相同
        if int(code) == int(smscode):
            user = User.query.filter_by(mobile=mobile).first()
            # 如果相同删除验证码 节约内存
            # 否则 存入到用户表中
            if user:
                r.del_key(mobile)
            else:
                u = User(mobile=mobile)
                db.session.add(u)
                db.session.commit()
                user = User.query.filter_by(mobile=mobile).first()
            # 生成token key加盐
            # 返回token给前端 用户id也返回给前端
            token = myjwt.jwt_encode({
                    'user_id':user.id,
                    'exp': int(time.time()) + 180
                })
            return jsonify({
                'code': 200,
                'msg': '登录成功',
                'token': token,
                'user_id': user.id
            })
        else:
            return jsonify({'code':400,'msg':'验证码错误'})
    else:
        return jsonify({'code':400,'msg':'验证码已过期'})

@user_blue.route('/wblogin')
def wblogin():
    client_id = '3674019597'
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({'code': 200, 'url': url})


@user_blue.route('/user/weiboCallback/')
def weiboCallback():
    # 获取token
    # 万能接收前端传参
    # req = reqparse.RequestParser()
    # req.add_argument('code')
    # args = req.parse_args()
    # code = args['code']

    # request.args.get获取前端参数
    code = request.args.get('code')
    print('code',code)

    # 向access_token接口发起post
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)

    # 解析参数，token、uid
    mes = json.loads(res.text)
    token = mes['access_token']
    uid = mes['uid']

    # 查询三方登录表中uid是否存在，如果存在，查询用户表，用户表信息生成token返回给vue
    sflogin = db.session.execute("select * from user inner join sflogin s on user.id = s.userid where s.uid=%s" % uid)
    sf = list(sflogin)
    # 获取的数据是个转换成list，里面的数据是值，根据索引获取
    if sf:
        for i in sf:
            token = myjwt.jwt_encode(data={'data': {'uid': i[0], 'exp': int(time.time())}})
            return redirect("http://localhost:8080/updatetoken?token=" + token + "&userid=" + str(i[0]))
    # 不存在跳转到vue绑定页面，token、uid传递过去
    else:
        return redirect("http://localhost:8080/bingmobile?token=" + str(token) + "&uid=" + str(uid))


@user_blue.route('/bingmobile', methods=['POST'])
def bingmobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    try:
        user = User(mobile=mobile)
        db.session.add(user)
        db.session.commit()
        uid = data['uid']
        token = data['token']
        # users= User.query.filter_by(mobile=mobile).first()
        # print(users)
        sf = sf_login(uid=uid, token=token, webfrom='微博', userid=int(user.id))
        db.session.add(sf)
        db.session.commit()
    except:
        return jsonify({'code': 10020, 'msg': '授权失败'})
    # 生成token
    token = myjwt.jwt_encode(data={'data': {'uid': user.id, 'exp': int(time.time())}})
    return jsonify({'code': 200, 'token': token, 'userid': user.id})















